package com.fjrz.bbxwj.main.video

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.baseUrl
import com.module.lemlin.rxhttp.msg
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.UploadResponse
import com.fjrz.bbxwj.entity.VideoCateList
import com.fjrz.bbxwj.entity.VideoRequest
import com.fjrz.bbxwj.mode.vm.VideoViewModel
import com.module.lemlin.view.DialogHintPopup
import com.fjrz.bbxwj.popup.ProgressPopup
import com.fjrz.bbxwj.popup.BottomPickerPopup
import com.fjrz.bbxwj.util.LocationUtils
import com.module.lemlin.rxhttp.code
import com.module.lemlin.view.LoadingDialog
import com.tbruyelle.rxpermissions3.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.fragment_video_editing.*

class VideoEditingFragment : ViewModeFragment<VideoViewModel>() {


    companion object {
        private const val EXTRA_NAME_VIDEO_REQUEST = "EXTRA_NAME_VIDEO_REQUEST"
        fun newInstance(videoRequest: VideoRequest): VideoEditingFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(EXTRA_NAME_VIDEO_REQUEST, videoRequest)
            }
            return VideoEditingFragment().apply { arguments = bundle }
        }

        enum class VideoAct(val type: Int) {
            ACT_1(type = 1),//直接上传
            ACT_2(type = 2),//存入草稿箱
            ACT_3(type = 3),//私人草稿箱
            ACT_4(type = 4)//保存
        }
    }

    private var mOldVideoRequest: VideoRequest = VideoRequest()

    private var mNewVideoRequest: VideoRequest = VideoRequest()

    private val mVideoType: MutableList<Picker> =
        mutableListOf(Picker(type = 1, name = "普通视频"), Picker(type = 2, name = "广告视频"))

    private val mVideoDraft: MutableList<Picker> =
        mutableListOf(Picker(type = 2, name = "视频草稿箱"), Picker(type = 3, name = "私人草稿箱"))


    private val mBottomCatePopup: BottomPickerPopup by lazy {
        BottomPickerPopup(context = requireContext(), onConfirm = { action, position ->
            val videoCateList: MutableList<VideoCateList>? =
                viewModel.videoCateTotalListLiveData.value?.httpData?.data
            if (videoCateList.isNullOrEmpty())
                return@BottomPickerPopup
            mNewVideoRequest.cate_id = videoCateList[position].id
            tvVideoEditCate.text = videoCateList[position].name
        })
    }

    private val mBottomTypePopup: BottomPickerPopup by lazy {
        BottomPickerPopup(context = requireContext(), onConfirm = { _, position ->
            mNewVideoRequest.type = mVideoType[position].type
            tvVideoEditType.text = mVideoType[position].name
            if (mVideoType[position].type == 1) {
                ivVideoEditImageLink.setImageResource(R.mipmap.ic_17630)
                etVideoEditTitleLink.text = null
                mNewVideoRequest.adv_title = null
                mNewVideoRequest.adv_image = null
                mNewVideoRequest.path_advert = null
                clVideoEditLink.visibility = View.GONE
            } else {
                val advImage: String? = mOldVideoRequest.adv_image
                if (advImage.isNullOrEmpty()) {
                    ivVideoEditImageLink.setImageResource(R.mipmap.ic_17630)
                } else ivVideoEditImageLink.loadRoundImage(
                    advImage, radius = ConvertUtils.dp2px((10f))
                )
                etVideoEditTitleLink.text = Editable.Factory.getInstance()
                    .newEditable((mOldVideoRequest.adv_title ?: ""))
                mNewVideoRequest.adv_title = mOldVideoRequest.adv_title
                mNewVideoRequest.adv_image = mOldVideoRequest.adv_image
                clVideoEditLink.visibility = View.VISIBLE
            }
        })
    }

    private val mBottomDraftPopup: BottomPickerPopup by lazy {
        BottomPickerPopup(context = requireContext(), onConfirm = { action, position ->
            if (mVideoDraft[position].type == 2) {
                if (!isVerificationFromCorrect())
                    return@BottomPickerPopup
                updateVideoData(VideoAct.ACT_2.type)
            } else if (mVideoDraft[position].type == 3) {
                if (!isVerificationFromCorrect())
                    return@BottomPickerPopup
                updateVideoData(VideoAct.ACT_3.type)
            }
        })
    }


    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = requireContext(), onConfirm = {

        }, onCancel = {
            mProgressPopup.dismiss()
            viewModel.dispose.clear()
        })
    }


    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = {
                hintPopup.dismiss()
                requireActivity().finish()
            },
            onCancel = {

            })
    }

    override fun viewModel(): VideoViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_video_editing

    override fun initView() {

        //视频分类选择
        tvVideoEditCate.setOnClickListener {
            val data: MutableList<String> = mutableListOf()
            viewModel.videoCateTotalListLiveData.value?.httpData?.data
                ?.forEach { data.add(it.name) }
            mBottomCatePopup.setFillData1(
                title = "请选择视频分类", pickers = data
            ).showPopupWindow()
        }
        //视频类型选择
        tvVideoEditType.setOnClickListener {
            val data: MutableList<String> = mutableListOf()
            when {
                mOldVideoRequest.type == 2 -> {
                    mVideoType.forEach { data.add(it.name) }
                }
                RZApplication.userInfoMe()?.is_certified_merchant ?: 0 != 1 -> {
                    mVideoType.filter { it.type != 2 }.forEach { data.add(it.name) }
                }
                else -> {
                    mVideoType.forEach { data.add(it.name) }
                }
            }
            mBottomTypePopup.setFillData1(
                title = "请选择视频类型", pickers = data
            ).showPopupWindow()
        }
        //草稿箱
        tvVideoEditBoxDraft.setOnClickListener {
            val data: MutableList<String> = mutableListOf()
            mVideoDraft.forEach { data.add(it.name) }
            mBottomDraftPopup.setFillData1(
                title = "请选择草稿箱", pickers = data
            ).showPopupWindow()
        }
        //链接图片选择
        ivVideoEditImageLink.setOnClickListener {
            val rxPermissions = RxPermissions(this)
            rxPermissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ).subscribe {
                if (!it) {
                    toast(message = "请到设置中开启相关权限")
                } else {
                    Matisse.from((this))
                        .choose(MimeType.ofImage())
                        .countable((true))
                        .maxSelectable(1)
                        .imageEngine(GlideEngine())
                        .theme(R.style.Matisse_Zhihu1)
                        .forResult((100))
                }
            }
        }
        //直接上传
        tvVideoEditUpload.setOnClickListener {
            if (!isVerificationFromCorrect())
                return@setOnClickListener
            updateVideoData(VideoAct.ACT_1.type)
        }
        //保存
        tvVideoEditSave.setOnClickListener {
            if (!isVerificationFromCorrect() && mNewVideoRequest.action != 2)
                return@setOnClickListener
            updateVideoData(VideoAct.ACT_4.type)
        }
        //发布
        tvVideoEditRelease.setOnClickListener {
            if (!isVerificationFromCorrect() && mNewVideoRequest.action != 2)
                return@setOnClickListener
            updateVideoData(VideoAct.ACT_1.type)
        }

//        //视频标题输入监听
//        etVideoEditTitle.addTextChangedListener {
//            mNewVideoRequest.title = it?.toString()
//        }
        //视频描述输入监听
        etVideoEditDesc.addTextChangedListener {
            mNewVideoRequest.description = it?.toString()
        }
        //链接标题输入监听
        etVideoEditTitleLink.addTextChangedListener {
            mNewVideoRequest.adv_title = it?.toString()
        }

        setFillData()
    }

    override fun initViewMode() {
        viewModel.uploadLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.START) {
                if (!mProgressPopup.isShowing)
                    mProgressPopup.showPopupWindow()
                mProgressPopup.resetProgress()
            } else if (response.status == Status.FAILURE) {
                mProgressPopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                when (it.type) {
                    UploadResponse.Type.FILE_IMAGE_AD -> {
                        mNewVideoRequest.adv_image = it.data.url
                        if (mNewVideoRequest.action == 2) {
                            mProgressPopup.dismiss()
                            viewModel.videoEdit(mNewVideoRequest.copy())
                        } else {
                            viewModel.commonUpload(
                                mNewVideoRequest.path_bitmap ?: "",
                                UploadResponse.Type.FILE_IMAGE_FRAME
                            )
                        }
                    }
                    UploadResponse.Type.FILE_IMAGE_FRAME -> {
                        mNewVideoRequest.main_image = it.data.url
                        viewModel.commonUpload(
                            mNewVideoRequest.path_video ?: "",
                            UploadResponse.Type.FILE_VIDEO
                        )
                    }
                    UploadResponse.Type.FILE_VIDEO -> {
                        mNewVideoRequest.path = it.data.url
                        mProgressPopup.dismiss()
                        viewModel.videoAdd(mNewVideoRequest.copy())
                    }
                }

            }
        })

        viewModel.progressLiveData.observe(this as LifecycleOwner, Observer { progress ->
            mProgressPopup.setProgress(progress)
        })

        viewModel.videoAddOrEditLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                hintPopup.isTextCancelGone(true)
                    .setText(
                        textTitle = "提示",
                        textMessage = it.msg,
                        textConfirm = "好的",
                        textCancel = null
                    ).setBackPressEnable(false)
                    .setOutSideDismiss(false)
                    .showPopupWindow()
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == AppCompatActivity.RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            ivVideoEditImageLink.loadRoundImage(
                pathList[0].apply { mNewVideoRequest.path_advert = this },
                radius = ConvertUtils.dp2px((10f))
            )
        }
    }

    private fun setFillData() {
        mOldVideoRequest = arguments?.getSerializable(EXTRA_NAME_VIDEO_REQUEST) as? VideoRequest
            ?: return
        LocationUtils.location(requireContext(), object : LocationUtils.OnSubAdminAreaListener {
            override fun onSubAdminArea(adminArea: String?, subAdminArea: String?) {
                mOldVideoRequest.province = adminArea ?: "福建省"
                mOldVideoRequest.city = subAdminArea ?: "福州市"
            }
        })
        mNewVideoRequest = mOldVideoRequest.copy(
            main_image = with(mOldVideoRequest.main_image) {
                if (this?.indexOf(baseUrl) == 0) replace(
                    baseUrl, ("")
                ) else this
            },
            path = with(mOldVideoRequest.path) {
                if (this?.indexOf(baseUrl) == 0) replace(
                    baseUrl, ("")
                ) else this
            },
            adv_image = with(mOldVideoRequest.adv_image) {
                if (this?.indexOf(baseUrl) == 0) replace(
                    baseUrl, ("")
                ) else this
            }
        )

        llVideoEditYes.visibility =
            if (mOldVideoRequest.action == 1) View.VISIBLE else View.INVISIBLE
        llVideoEditNot.visibility =
            if (mOldVideoRequest.action == 2) View.VISIBLE else View.INVISIBLE
        viewModel.videoCateTotalListLiveData.value?.httpData?.data?.let { cateList ->
            cateList.find { it.id == mOldVideoRequest.cate_id }?.let {
                tvVideoEditCate.text = it.name
            }
        }
//        mOldVideoRequest.title?.let {
//            etVideoEditTitle.text = Editable.Factory.getInstance().newEditable(it)
//        }
        mOldVideoRequest.description?.let {
            etVideoEditDesc.text = Editable.Factory.getInstance().newEditable(it)
        }
        if (mOldVideoRequest.type == 1) {
//            tvVideoEditType.text = "普通视频"
            clVideoEditLink.visibility = View.GONE
        } else if (mOldVideoRequest.type == 2) {
//            tvVideoEditType.text = "广告视频"
            clVideoEditLink.visibility = View.VISIBLE
        }
        if (mOldVideoRequest.type == 2) mOldVideoRequest.adv_title?.let {
            etVideoEditTitleLink.text = Editable.Factory.getInstance().newEditable(it)
        }
        if (mOldVideoRequest.type == 2) mOldVideoRequest.adv_image?.let {
            ivVideoEditImageLink.loadRoundImage(it, radius = ConvertUtils.dp2px((10f)))
        }
        if (mOldVideoRequest.action == 1) mOldVideoRequest.path_bitmap?.let {
            ivVideoEditImageFrame.loadRoundImage(it, radius = ConvertUtils.dp2px((10f)))
        } else if (mOldVideoRequest.action == 2) mOldVideoRequest.main_image?.let {
            ivVideoEditImageFrame.loadRoundImage(it, radius = ConvertUtils.dp2px((10f)))
        }
    }

    private fun isVerificationFromCorrect(): Boolean {
        val fromError: String? = if (mNewVideoRequest.cate_id == 0) {
            "请选择视频分类"
        }
//        else if (mNewVideoRequest.title.isNullOrEmpty()) {
//            "请输入视频标题"
//        }
        else if (mNewVideoRequest.description.isNullOrEmpty()) {
            "请输入视频描述"
        } else if (mNewVideoRequest.type == 0) {
            "请选择视频类型"
        } else if (mNewVideoRequest.type == 2 && mNewVideoRequest.adv_title.isNullOrEmpty()) {
            "请输入链接标题"
        } else if (mNewVideoRequest.type == 2 && mNewVideoRequest.action == 1 && mNewVideoRequest.path_advert.isNullOrEmpty()) {
            "请选择链接图片1"
        } else if (mNewVideoRequest.type == 2 && mNewVideoRequest.action == 2 && mNewVideoRequest.path_advert.isNullOrEmpty() && mNewVideoRequest.adv_image.isNullOrEmpty()) {
            "请选择链接图片2"
        } else null
        if (!fromError.isNullOrEmpty()) {
            toast(message = fromError)
        }
        return fromError.isNullOrEmpty()
    }

    private fun updateVideoData(act: Int) {
        mNewVideoRequest.act = act.toString()
        val pathAdvert: String? = mNewVideoRequest.path_advert
        val pathBitmap: String? = mNewVideoRequest.path_bitmap
        if (mNewVideoRequest.type == 2 && !pathAdvert.isNullOrEmpty()) {
            viewModel.commonUpload(pathAdvert, UploadResponse.Type.FILE_IMAGE_AD)
        } else if (mNewVideoRequest.type == 1 && !pathBitmap.isNullOrEmpty()) {
            viewModel.commonUpload(pathBitmap, UploadResponse.Type.FILE_IMAGE_FRAME)
        } else if (mNewVideoRequest.action == 1) {
            viewModel.videoAdd(mNewVideoRequest.copy())
        } else if (mNewVideoRequest.action == 2) {
            viewModel.videoEdit(mNewVideoRequest.copy())
        }
    }


    private fun responseStatus2LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) LoadingDialog.show(
            context = requireContext(), resId = R.layout.dialog_load_style_1
        ) else if (status == Status.FAILURE) {
            LoadingDialog.dismiss()
            toast(throwable?.code, throwable?.msg)
        } else {
            LoadingDialog.dismiss()
        }
        return status
    }

    data class Picker(val type: Int, val name: String)
}